import axios from "axios";
import { Consts, DeviceInfo, DeviceType, FeederSetting, FeedingRecord } from "./entities";
import router from '../router';
import * as atom from './atom';
export interface ReturnObject{
    code: number;   //错误码
    msg: string;    //错误信息
    data: object|null|any|undefined;    //返回的数据
}

export class IotApi{
    //
    public static ERR_TIME_OUT = 303;

    //负责api的访问和会话的管理
    private static base_url: string;
    private static token: string;
    private static login_name: string;
    private static pwd: string;
    public static debug: boolean = true;
    public static init(base_url: string){
        IotApi.base_url = base_url;
    }

    private static goto_page(page_path: string){
        IotApi.log('goto_page：', page_path);
        router.replace({path: page_path});
    }

    private static go_home(){
        IotApi.goto_page('/login');
    }

    private static log(...data: any[]): void{
        //控制日志的输出
        if(IotApi.debug){
            console.log(data);
        }
    }

    public static logined(): boolean{
        //判断是否已经登录
        return (IotApi.token && IotApi.token.length>0);
    }

    public static async post(path: string, data: object|null|undefined, auth: boolean=true): Promise<ReturnObject>{
        /*功能：
        path：路径，data：载荷，auth：是否需要权限
        1、发送post请求；
        2、自动填充token；
        3、会话超时自动跳转到登录页面；
        4、出现异常显示提示信息；
        */
        IotApi.log('post：', path, data, auth);
        try{
            //初始化headers
            const headers = {'Content-Type': 'application/json'};
            if(auth==true){
                if(IotApi.token==undefined || IotApi.token==null){
                    alert('请先系统登录');
                    IotApi.go_home();
                }
                headers['token']=IotApi.token;
            }
            //发起网络请求
            const response = await axios.post('/api'+path, data, {headers});
            if (response.status == 200){
                var rd = response.data;
                IotApi.log(rd);
                if([330, 300].includes(rd.code)){
                    alert(rd.msg);
                    IotApi.go_home();
                }
                return rd as ReturnObject;
            }
            const obj = new Object() as ReturnObject;
            return {code:-1, msg:`${path}网络请求失败${response.status}`} as ReturnObject;
        }catch(error){
            IotApi.log(path, error);
            return {code:-1, msg:`请求失败${error}`} as ReturnObject;
        }
    }

    //登录
    public static async login(login_name: String, pwd: String):Promise<ReturnObject>{
        const path = '/iot/login';
        const data = {
            'username': login_name,
            'password': pwd
        }
        const obj: ReturnObject = await IotApi.post(path, data, false);
        if(obj && obj.code==0){
            IotApi.token = obj.data.token;
        }
        return obj;
    }
    //获取设备类型列表
    public static async get_device_types():Promise<DeviceType[]>{
        const path = '/iot/get-device-types';
        const post_data = {
        };
        const ro = await IotApi.post(path, {}, true);
        if(ro.code==0 && Array.isArray(ro.data)){
            let ret: DeviceType[] = [];
            for(let i=0; i<ro.data.length; i++){
                ret.push(ro.data[i] as DeviceType);
            }
            return ret;
        }else{
            throw new Error(`获取设备数据失败${ro.code}, ${ro.msg}`);
        }
    }
    //获取设备列表信息
    public static async get_device_list():Promise<DeviceInfo[]>{
        const path = '/iot/get-devices';
        const post_data = {
        };
        const ro = await IotApi.post(path, {}, true);
        if(ro.code==0 && Array.isArray(ro.data)){
            let ret: DeviceInfo[] = [];
            for(let i=0; i<ro.data.length; i++){
                ret.push(ro.data[i] as DeviceInfo);
            }
            return ret;
        }else{
            throw new Error(`获取设备数据失败${ro.code}, ${ro.msg}`);
        }
    }
    //发送消息
    public static async send_msg(device_id: string, action: string, data: object):Promise<ReturnObject>{
        const path = '/iot/sendmessage';
        const post_data = {
            'device_id': device_id,
            'action': action,
        };
        if(data!=null){
            post_data['data'] = data;
        }
        return IotApi.post(path, post_data, true);
    }
    //获取最新消息
    public static async get_last_msg(device_id: string, action: string):Promise<ReturnObject>{
        const path = '/iot/getlastmessage'
        const post_data = {
            'device_id': device_id,
            'action': action
        };
        return IotApi.post(path, post_data, true);
    }
    //获取消息列表
    public static async get_msg_list(device_id: string, action: string, sender: string, page_no: number, page_size: number):Promise<ReturnObject>{
        const path = '/iot/getmessages'
        const post_data = {
            'device_id': device_id,
            'action': action,
            'sender': sender,
            'page_no': page_no,
            'page_size': page_size
        };
        return IotApi.post(path, post_data, true);
    }

    //获取宠物喂食器的喂食设置
    public static async get_feeder_setting(device_id: string):Promise<FeederSetting[]>{
        const path = '/iot/getlastmessage'
        const post_data = {
            'device_id': device_id,
            'action': 'setting'
        };
        const rt = await IotApi.post(path, post_data, true);
        let ret = [];
        if(rt.code==0 && Array.isArray(rt.data)){
            for(let i=0; i<rt.data.length; i++){
                const setting = rt.data[i] as FeederSetting;
                ret.push(setting);
            }
        }
        return ret;
    }

    //激活设备
    public static async active_device(device_name: string, active_code: string):Promise<ReturnObject>{
        const path = '/iot/active-device'
        const post_data = {
            'device_name': device_name,
            'active_code': active_code
        };
        const rt = await IotApi.post(path, post_data, true);
        return rt as ReturnObject;
    }

    //绑定设备
    public static async bind_device(device_id: string):Promise<ReturnObject>{
        const path = '/iot/bind-device'
        const post_data = {
            'device_id': device_id
        };
        const rt = await IotApi.post(path, post_data, true);
        return rt as ReturnObject;
    }

    //修改设备名称
    public static async modify_device_name(device_id: string, device_name: string): Promise<ReturnObject>{
        const path = '/iot/modify-device-name'
        const post_data = {
            'device_id': device_id,
            'device_name': device_name
        }
        const rt = await IotApi.post(path, post_data, true);
        return rt as ReturnObject;
    }

    public static async get_feeding_records(device_id: string, from: string, to: string, page_no: number, page_size: number):Promise<FeedingRecord[]>{
        //获取喂食记录
        const rt = await IotApi.get_msg_list(device_id, 'feeding', null, page_no, page_size);
        if(rt.code==0){
            const msg_count: number = rt.data.msgs.length;
            const msgs = rt.data.msgs;
            let feedings:FeedingRecord[] = [];
            for(var i=0; i<msg_count; i++){
                const msg = msgs[i];
                const feeding = {time: msg.time, set: msg.data.set} as FeedingRecord;
                feedings.push(feeding);
            }
            return feedings;
        }else{
            throw new Error(rt.msg);
        }
    }

    public static feed(device_id: string){
        //获取喂食记录

        const rec = {set: 1};
        IotApi.send_msg(device_id, 'feed', rec).then((value)=>{
            if(value.code==0){
                alert('指令已发出');
            }else{
                alert(value.msg);
            }
        },(reason)=>{
            alert(reason);
        }).catch((reason)=>{
            alert(reason);
        })
    }
}

// async function get_device_types(): Promise<DeviceType[]>{
//     try{
//         const response = await axios.post('/api/iot/get-device-types');
//         var data = response.data;
//         console.log(data);
//         if (data.code!=undefined && data.code==0 && data.data){
//             console.log("OK");
//             return data.data as DeviceType[];
//         }
//         return [];
//     }catch(error){
//         console.log('get_device_types', error);
//     }
//     return []
// }

// export{get_device_types}
